<template>
  <el-container>
    <el-header>
      <div class="report_header" ref="headerHeight">
        <div class="report_header_left"></div>

        <div style="display: flex;flex-direction: row;justify-content:space-between;;width: 100%;">
          <div style="display: flex;flex-direction: row;flex-wrap: wrap;overflow: hidden;height:41px;justify-content: space-between;">

            <div class="report_header_query">
               <search-options ref="optionsRef" :tips-text="'请选择水票'" :request="'bom'" :fixed-params="{'type': 2}" :request-key-value="{key: 'productName', value: 'productName'}" @getValue="queryProductName" />
             </div>
           </div>
           <div>
             <div style="display: flex">
               <div class="report_header_date">
                 <el-input prefix-icon="el-icon-search" placeholder="商品名称/货号/条码" v-model="query.keyword" clearable></el-input>
               </div>
           <el-button style="margin-left: 10px;" size="small" type="primary" :loading="queryClicked" @click="queryClick">查询</el-button>
          <el-button style="margin-left: 10px" size="small" type="primary" @click="showDialog" v-permission="['waterTicket.add']">新增</el-button>
           <el-button type="warning"  size="small"  style="margin-left: 10px;" @click=Waterticket>一键添加水票</el-button>
             </div>
           </div>
        </div>
      </div>
    </el-header>
    <div class="pd10">
      <el-table v-loadMore="[payLoads,'bom-list']" :data="bomList" border stripe :height="curHeight" style="width: 100%">
        <el-table-column label="缩略图" align="center" width="80">
          <template slot-scope="scope">
            <img style="width: 50px; height: 50px; vertical-align:middle; overflow: hidden;" :src="scope.row.productThumbnail" alt="">
          </template>
        </el-table-column>
        <el-table-column label="编码" width="150" align="left" prop="sn" />
        <el-table-column label="水票名称" align="left" prop="productName" />
        <el-table-column label="销售价" width="110" align="left" prop="productPrice" />
        <el-table-column label="单位" width="80" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.unit }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80" align="center" prop="isMarketable">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isMarketable ?'primary':'danger'">
                <span>{{ scope.row.isMarketable | watchType }}</span>
              </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center" width="70" prop="orders" :render-header="ordersIcons">
          <template slot-scope="scope">
            <el-input v-model="scope.row.orders" @blur="bulrOrders(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="功能" align="center" fixed="right" width="80">
          <template slot-scope="scope">
            <el-button v-if="scope.row.isMarketable" v-permission="['waterTicket.down']" :type="scope.row.isMarketable ?'primary':'danger'" size="mini" @click="releaseBom(scope.row)">
              下架
            </el-button>
            <el-button v-else v-permission="['waterTicket.up']" :type="scope.row.isMarketable ?'primary':'danger'" size="mini" @click="releaseBom(scope.row)">
              上架
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" align="center" width="80">
          <template slot-scope="scope">
            <div>
              <el-tooltip v-permission="['waterTicket.edit']" class="item" effect="dark" content="编辑" placement="top-start">
                <a @click="editClick(scope.row)">
                  <i style="color: #409EFF" class="el-icon-edit" />
                </a>
              </el-tooltip>
              <el-tooltip v-permission="['waterTicket.del']" class="item" effect="dark" content="删除" placement="top-start">
                <a style="margin-left: 10px" @click="deleteBom(scope.row)">
                  <i style="color: #F56C6C" class="el-icon-delete" />
                </a>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-footer class="el-footerBox">
      <pagination v-show="total>0" :total="total" :page.sync="pageNum" :limit.sync="pageSize" @pagination="loadBom" />
    </el-footer>

    <el-dialog width="450px" title="添加水票" :visible.sync="addFormVisible">
      <el-form ref="addFormRef" style="margin: 30px 0;" :model="addForm" :rules="addFormRules" label-width="80px">
        <el-form-item prop="productId" label="桶装水">
          <search-options ref="optionsRef" :tips-text="'请选择桶装水'" :options-style="'width: 80%'" :request="'product'" :fixed-params="addFixedParams" @getValue="addQueryProduct" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addFormVisible = false">取 消</el-button>
        <el-button v-permission="['waterTicket.add']" :loading="addClicked" type="primary" @click="addClick">确 定</el-button>
      </div>
    </el-dialog>

  </el-container>
</template>

<script>
import loadMore from '@/utils/loadMore.js'
import permission from '@/directive/permission/index.js' // 权限判断指令
import { list, addWater, del, batchAddWater } from '@/api/waterTicket'
import { updateProduct } from '@/api/product'
import { list as productCategory } from '@/api/productCategory'
import Pagination from '@/components/Pagination'
import searchOptions from '@/components/searchOptions'
import { EventBus } from '@/api/eventBus'

export default {
  name: 'BomList',
  directives: { permission, loadMore },
  components: { Pagination, searchOptions },
  filters: {
    watchType(val) {
      if (val === false) {
        return '未上架'
      } else if (val === true) {
        return '已上架'
      }
    }
  },
  data() {
    return {
      queryType: true,
      productCategoryList: [],

      query: {
        sysMchId:'',
        keyword: ''
      },
      keyword: {
        keyword: ''
      },
      pageNum: 1,
      pageSize: 20,
      total: 0,
      queryClicked: false,
      resetClicked: false,
      addClicked: false,
      curHeight: null,
      payLoads: '',
      addFixedParams: {
        'type': 0,
        'isList': true,
      },
      addForm: {
        productId: '',
        productCategoryId: ''
      },
      addFormRules: {
        productId: [
          { required: true, message: '请选择商品名称', trigger: 'blur' }
        ],
        productCategoryId: [
          { required: true, message: '请选择商品分类', trigger: 'change' }
        ]
      },
      addFormVisible: false,
      bomList: []
    }
  },
  activated() {
    this.payLoads = new Date().getTime()
  },
  created() {
    this.loadBom()
  },
  mounted() {
    this.comeIn()
    this.beforeMount()
  },
  methods: {
    Waterticket(){
       batchAddWater().then(res=>{
          if(res.type='success'){
                this.$message('一键添加成功');
                this.loadBom()
          }else{
             this.$message({
          message: '一键添加失败',
          type: 'warning'
        });
          }
       })
    },

    beforeMount() {
      var _this = this
      window.onresize = () => {
        return (() => {
          var h = document.documentElement.clientHeight || document.body.clientHeight
          if (this.queryType === false) {
            _this.curHeight = h - 266// 减去页面上固定高度height
          } else {
            _this.curHeight = h - 220// 减去页面上固定高度height
          }
        })()
      }
    },
    comeIn() {
      console.log('222')
      var h = document.documentElement.clientHeight || document.body.clientHeight
      this.curHeight = h - 220// 减去页面上固定高度height
    },
    chooseClick() {
      this.queryType = !this.queryType
      var h = document.documentElement.clientHeight || document.body.clientHeight
      if (this.queryType === false) {
        this.curHeight = h - 266// 减去页面上固定高度height
      } else {
        this.curHeight = h - 220// 减去页面上固定高度height
      }
    },
    queryClick() {
      this.queryClicked = true
      this.keyword = this.query
      this.pageNum = 1
      this.loadBom()
    },
    resetClick() {
      this.resetClicked = true
      this.$refs.optionsRef.resetValue()
      this.pageNum = 1
      this.loadBom()
    },
    queryProductName(value) { // 查询商品
      this.query.itemProductName = value
    },
    addQueryProduct(value) { // 添加的查询商品
      this.addForm.productId = value
    },
    showDialog() {
      this.addFormVisible = true
    },
    addClick() { // 新增
      this.$refs['addFormRef'].validate((valid) => {
        if (valid) {
          this.addClicked = true
          addWater({ productId: this.addForm.productId, productCategoryId: this.addForm.productCategoryId }).then(res => {
            console.log(res)
            this.loadBom()
            this.addFormVisible = false
            this.addClicked = false
          }).catch(() => { this.addClicked = false })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 上架
    releaseBom(row) {
      this.$confirm(row.isMarketable ? '确认下架?' : '确认上架?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateProduct({
          id: row.productId,
          isMarketable: !row.isMarketable
        }).then(res => {
          console.log(res)
          for (let i = 0; i < this.bomList.length; i++) {
            if (this.bomList[i].productId == res.data.id) {
              this.bomList[i].isMarketable = res.data.isMarketable
            }
          }
          this.$message({ type: 'success', message: row.isMarketable ? '上架成功' : '下架成功' })
        }).catch(() => {})
      }).catch(() => {
        this.$message({ type: 'info', message: row.isMarketable ? '已取消下架' : '已取消上架'})
      })
    },
    //  编辑
    editClick(row) {
      this.$router.push({
        path: '/waterTicket/edit?id=' + row.productId
      })
    },

    loadBom() {
      const params = new URLSearchParams()
      params.append('pageNum', this.pageNum)
      params.append('pageSize', this.pageSize)
      params.append('mchId',this.query.sysMchId)
      params.append('type', 2)
      params.append('itemProductName', this.keyword.keyword)
      list(params).then(res => {
        console.log(res)
        this.queryClicked = false
        this.resetClicked = false
        this.bomList = res.data.data
        this.total = res.data.total
      }).catch(() => {
        this.queryClicked = false
        this.resetClicked = false
      })
    },
    deleteBom(data) {
      console.log(data)
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(data.id).then(res => {
          console.log(res)
          this.bomList.forEach((item, index) => {
            if (item.id === data.id) {
              this.bomList.splice(index, 1)
            }
          })
          this.$message({
            message: res.content,
            offset: 120,
            center: true
          })
        }).catch(() => {})
      }).catch(() => {})
    },
    ordersIcons(h, { column }) { // 排序
      const inReview = '点击下方数字区域可直接更改排序。'
      return h('div', [
        h('span', column.label),
        h(
          'el-tooltip',
          {
            props: {
              placement: 'top'
            }
          },
          [
            h(
              'div',
              {
                slot: 'content',
                style: {
                  width: '200px',
                  whiteSpace: 'normal',
                  'margin-bottom': '10px'
                }
              },
              inReview
            ),
            h('i', {
              class: 'el-icon-question',
              style: 'color:#888888;margin-left:5px;position:absolute'
            })
          ]
        )
      ])
    },
    bulrOrders(data) {
      console.log(data)
      updateProduct({
        id: data.productId,
        orders: data.product.orders,
        isMarketable: data.isMarketable
      }).then(res => {
        console.log(res)
      }).catch(() => {})
    }
  }
}
</script>
<style scoped>
  .el-footerBox {
    height: 50px !important;
    line-height: 50px !important;
    border-top: 1px solid #eeeeee;
  }

  /deep/ .el-dialog__header {
    border: 1px solid #eeeeee !important;
    padding: 15px !important;
  }

  /deep/ .el-dialog__body {
    padding: 0px 20px !important;
  }

  .popup_content {
    padding-bottom: 0px !important;
  }

  .app {
    background-color: rgba(248, 248, 248, 0.8);
  }
  /deep/.el-header {
    padding: 10px;
    /* height: 100% !important; */
    padding-bottom: 0;
  }
  .report_header {
    width: 100%;
    min-height: 40px;
    box-sizing: border-box;
    background-color: rgba(248, 248, 248, 0.8);
    display: flex;
    align-items: center;
    padding-bottom: 5px;
    position: relative;
    padding-left: 5px;
    padding-right: 5px;
  }


  .report_header_left {
    width: 5px;
    height: 100%;
    background-color: #409EFF;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
  }

  .report_header_query {
    margin-left: 10px;
    width: 180px;
    margin-top: 5px;
  }
</style>
